package com.ygxsk.carhome.ui.park;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.ParkingSpaceAdapter;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2024/1/6  11:44
 * @Description:选择车位列表，选择了一个车位之后，再添加车辆
 */
public class ParkingSelectSpaceActivity extends ErrorActivity implements ErrorParentExtraSingle {


    private ArrayList<ParkingSpaceBean> mDataResources = new ArrayList<>();

    @BindView(R.id.refreshlayoutinparkspace)
    SmartRefreshLayout refreshLayoutInParkspace;

    @BindView(R.id.recyclerviewparkspace)
    RecyclerView recyclerviewParkspace;

    //当前界面的适配器内容
    private ParkingSpaceAdapter parkingSpaceAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        //填充
        initloading();

        initViews();

        gainDatas();


    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_parking_select_space;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.title_repair_choose_place));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                methodBack();
            }
        });

        //这里右上角没有东西的
        toolbarHelper.setLayoutRight(true, 0, "", null);

        //添加潜在客户的按钮
//        toolbarHelper.setLayoutRight(true, 0, "添加", new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//
//                //快速双加的限制，
//                // : 2023-07-11 16:18 添加预约维保的信息，到提交表单页面；
//                Bundle extra_bundle = new Bundle();
////                ActivityUtils.startActivity(extra_bundle, LeadAddSubmitActivity.class);
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {

        //填充列表和刷新
        MyLinearLayoutManager manager = new MyLinearLayoutManager(this);
        recyclerviewParkspace.setLayoutManager(manager);
        //普通的填充列表内容
        parkingSpaceAdapter = new ParkingSpaceAdapter(R.layout.parkingspaceadapter, mDataResources);
        recyclerviewParkspace.setLayoutManager(new MyLinearLayoutManager(this));

        recyclerviewParkspace.setAdapter(parkingSpaceAdapter);
        parkingSpaceAdapter.notifyDataSetChanged();

        //仅仅是文本点击内容的监听
        parkingSpaceAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                ParkingSpaceBean parkingSpaceBean = (ParkingSpaceBean) adapter.getItem(position);

                if (parkingSpaceBean != null) {

                    Bundle bundle_extra = new Bundle();

                    //携带 该小区的车位id等信息
                    bundle_extra.putString(ExtraKey.EXTRA_PARKINGSPACEID, parkingSpaceBean.getParkingSpaceId());

                    ActivityUtils.startActivity(bundle_extra, ParkingBundleActivity.class);

                }

            }
        });


        //下拉刷新的控件内容
        refreshLayoutInParkspace.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        gainDatas();

                        refreshLayout.finishRefresh();

                    }
                });

            }
        });

    }

    @Override
    protected void gainDatas() {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
//        map.put(Parameterkey.status, RepairStatusUpLoadType.STATE_HAS_DISPATCH.getIndex());//状态


//        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
//        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETAPPPARKLISTFORREMOTE_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getAppParkListForRemote_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getAppParkListForRemote(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(ParkingSelectSpaceActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<ParkingSpaceBean>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        methodNotSuccessData(what_method, serverCode, serverMessage);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        loadingGone();
//                        if (refreshLayoutInRepairManageListHistory != null) {
//                            refreshLayoutInRepairManageListHistory.setEnableLoadMore(true);
//                        }
                    }
                }).subscribe(new Consumer<ArrayList<ParkingSpaceBean>>() {
                    @Override
                    public void accept(ArrayList<ParkingSpaceBean> parkingSpaceBeanArrayList) throws Throwable {

                        if (mDataResources != null && !mDataResources.isEmpty()) {
                            mDataResources.clear();
                        }

                        if (parkingSpaceBeanArrayList != null && !parkingSpaceBeanArrayList.isEmpty()) {
                            if (mDataResources != null) {
                                mDataResources.addAll(parkingSpaceBeanArrayList);
                            }
                        }

                        if (parkingSpaceAdapter != null) {
                            parkingSpaceAdapter.notifyDataSetChanged();
                        }

                    }


                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //页面报错；
                        function_apiException(apiException);

                    }
                });


    }

    @Override
    protected void methodBack() {
        methodBackFinish();
    }

    @Override
    public void processExtraData() {

        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

            //

        }

    }
}